package com.panling.daohang

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.location.Criteria
import android.location.Geocoder
import android.location.Location
import android.location.LocationRequest
import android.os.Build
import android.os.Bundle
import android.os.Looper
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.annotation.RequiresApi
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.Utils
import com.huawei.hmf.tasks.OnFailureListener
import com.huawei.hmf.tasks.OnSuccessListener
import com.huawei.hms.location.FusedLocationProviderClient
import com.huawei.hms.location.LocationCallback
import com.huawei.hms.location.LocationResult
import com.huawei.hms.location.LocationServices
import com.huawei.hms.location.LocationSettingsRequest
import java.text.SimpleDateFormat
import java.util.Date
import java.util.concurrent.TimeUnit


class MainActivity : ComponentActivity() {

    private lateinit var mLocationRequest: com.huawei.hms.location.LocationRequest

    // 定位交互接入对象
    private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
    private fun getPermission(){
        PermissionUtils.permissionGroup(PermissionConstants.LOCATION)
            .rationale { activity, shouldRequest ->  }
            .callback(object : PermissionUtils.FullCallback {
                override fun onGranted(permissionsGranted: List<String>) {
                    LogUtils.d(permissionsGranted)
                }

                override fun onDenied(permissionsDeniedForever: List<String>,
                                      permissionsDenied: List<String>) {
                    LogUtils.d(permissionsDeniedForever, permissionsDenied)
                }
            })
            .theme { activity -> ScreenUtils.setFullScreen(activity) }
            .request()
    }

    private lateinit var tvLocation: TextView

    companion object{
        const val TAG = "MainActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_article)
        getPermission()
        checkLocationSettings()
            
        findViewById<Button>(R.id.btnStart).setOnClickListener {
//            startLocation()
        }
        updateLocation()

        tvLocation = findViewById<TextView>(R.id.tvLocation)

    }

    private fun updateLocation(){
        ThreadUtils.executeBySingleAtFixRate(object : ThreadUtils.SimpleTask<Int>(){
            override fun doInBackground(): Int {
                startLocation()
                return 0
            }

            override fun onSuccess(p0: Int?) {

            }
        },2,TimeUnit.SECONDS)
    }


    private fun checkLocationSettings(){
        val builder = LocationSettingsRequest.Builder()
        mLocationRequest = com.huawei.hms.location.LocationRequest()
        mLocationRequest.interval = 0
//        mLocationRequest.priority = LocationRequest.QUALITY_HIGH_ACCURACY
        builder.addLocationRequest(mLocationRequest)
        val locationSettingsRequest = builder
            .build()
        LocationServices.getSettingsClient(this).checkLocationSettings(locationSettingsRequest)
            .addOnSuccessListener { locationSettingsResponse ->
                val locationSettingsStates = locationSettingsResponse.locationSettingsStates
                val stringBuilder = StringBuilder()
                stringBuilder.append("isLocationUsable=").append(locationSettingsStates.isLocationUsable)
                stringBuilder.append(",\nisHMSLocationUsable=")
                    .append(locationSettingsStates.isHMSLocationUsable)
                Log.i(TAG, "checkLocationSetting onComplete:$stringBuilder")
            }
            .addOnFailureListener { e ->
                Log.i(TAG, "checkLocationSetting onFailure:" + e.message)
            }


        val builder1 = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val notificationChannel =
                NotificationChannel(packageName, "LOCATION", NotificationManager.IMPORTANCE_LOW)
            notificationManager.createNotificationChannel(notificationChannel)
            Notification.Builder(this, packageName)
        } else {
            Notification.Builder(this)
        }
        val mNotification = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            builder1.build()
        } else {
            builder1.notification
        }
        // 实例化fusedLocationProviderClient对象
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
        fusedLocationProviderClient.enableBackgroundLocation(1,mNotification)

    }


    private fun startLocation(){
        fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
            .addOnSuccessListener {
                Log.i(TAG, "startLocation success:")
            }
            .addOnFailureListener {
                Log.i(TAG, "startLocation fail:$it")
            }
    }

    private val mLocationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult
        ) {
            locationResult.locations.forEachIndexed { index, location ->
                runOnUiThread {
                    tvLocation.text = "Latitude  index:$index   ,latitude: ${location.latitude}, longitude: ${location.longitude}"
                }
            }
        }
    }


    private fun removeLocation(){
        fusedLocationProviderClient.disableBackgroundLocation()
        fusedLocationProviderClient.removeLocationUpdates(mLocationCallback)
            .addOnSuccessListener {
                Log.i(TAG, "removeLocation success:")
            }
            .addOnFailureListener {
                Log.i(TAG, "removeLocation error:$it")
            }
    }

    override fun onDestroy() {
        super.onDestroy()
        removeLocation()
    }

}



